package com.lsh.radardemo;

import android.content.Context;
import android.hardware.usb.UsbDevice;
import android.hardware.usb.UsbDeviceConnection;
import android.hardware.usb.UsbManager;
import android.opengl.GLSurfaceView;
import android.os.Bundle;
import android.os.Handler;
import android.os.Looper;
import android.util.Log;
import android.widget.TextView;
import android.widget.Toast;

import androidx.annotation.Nullable;
import androidx.appcompat.app.AppCompatActivity;

import com.felhr.usbserial.UsbSerialDevice;
import com.felhr.usbserial.UsbSerialInterface;

import java.util.Arrays;
import java.util.HashMap;
import java.util.Map;

public class Senser extends AppCompatActivity {

    private static final String TAG = "GyroSensor";
    private static final String VID = "1a86";
    private static final String PID = "7523";

    // UI组件
    private TextView rollTextView, pitchTextView, yawTextView;
    private TextView gyroXTextView, gyroYTextView, gyroZTextView;

    // 新增OpenGL相关变量
    private GLSurfaceView mGLSurfaceView;
    private GyroRenderer mRenderer;

    // USB相关
    private UsbManager usbManager;
    private UsbDevice device;
    private UsbSerialDevice serialPort;
    private UsbDeviceConnection connection;

    // 主线程Handler
    private final Handler mainHandler = new Handler(Looper.getMainLooper());

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_senser);
        initViews();

        // 初始化OpenGL
        initOpenGL();

        initUsbConnection();

        // 添加返回主界面按钮点击事件
        android.widget.Button btnBack = findViewById(R.id.btnBack);
        btnBack.setOnClickListener(v -> finish());
    }
    private void initViews() {
        rollTextView = findViewById(R.id.roll_text);
        pitchTextView = findViewById(R.id.pitch_text);
        yawTextView = findViewById(R.id.yaw_text);
        gyroXTextView = findViewById(R.id.gyro_x_text);
        gyroYTextView = findViewById(R.id.gyro_y_text);
        gyroZTextView = findViewById(R.id.gyro_z_text);
        // 初始化GLSurfaceView
        mGLSurfaceView = findViewById(R.id.gl_surface_view);
    }


    private void initOpenGL() {
        // 创建OpenGL ES 2.0上下文
        mGLSurfaceView.setEGLContextClientVersion(2);

        // 设置渲染器
        mRenderer = new GyroRenderer();
        mGLSurfaceView.setRenderer(mRenderer);

        // 设置渲染模式为持续渲染
        mGLSurfaceView.setRenderMode(GLSurfaceView.RENDERMODE_CONTINUOUSLY);
    }

    private void initUsbConnection() {
        usbManager = (UsbManager) getSystemService(Context.USB_SERVICE);
        scanAndConnectUsbDevice();
    }

    private void scanAndConnectUsbDevice() {
        HashMap<String, UsbDevice> usbDevices = usbManager.getDeviceList();
        if (usbDevices.isEmpty()) {
            showToast("没有检测到USB设备");
            return;
        }

        for (Map.Entry<String, UsbDevice> entry : usbDevices.entrySet()) {
            device = entry.getValue();
            if (isTargetDevice(device)) {
                if (hasUsbPermission()) {
                    setupSerialConnection();
                } else {
                    showToast("请授予USB权限");
                }
                return;
            }
        }
        showToast("未找到匹配的USB设备");
    }

    private boolean isTargetDevice(UsbDevice device) {
        String deviceVid = Integer.toHexString(device.getVendorId());
        String devicePid = Integer.toHexString(device.getProductId());
        return deviceVid.equalsIgnoreCase(VID) && devicePid.equalsIgnoreCase(PID);
    }

    private boolean hasUsbPermission() {
        return usbManager.hasPermission(device);
    }

    private void setupSerialConnection() {
        connection = usbManager.openDevice(device);
        serialPort = UsbSerialDevice.createUsbSerialDevice(device, connection);

        if (serialPort != null && serialPort.open()) {
            configureSerialPort();
            showToast("串口连接成功");
        } else {
            showToast("无法打开串口");
        }
    }

    private void configureSerialPort() {
        serialPort.setBaudRate(115200);
        serialPort.setDataBits(UsbSerialInterface.DATA_BITS_8);
        serialPort.setStopBits(UsbSerialInterface.STOP_BITS_1);
        serialPort.setParity(UsbSerialInterface.PARITY_NONE);
        serialPort.setFlowControl(UsbSerialInterface.FLOW_CONTROL_OFF);
        serialPort.read(dataCallback); // 注册数据回调
    }

    private final UsbSerialInterface.UsbReadCallback dataCallback = new UsbSerialInterface.UsbReadCallback() {
        private byte[] buffer = new byte[1024];
        private int bufferPos = 0;

        @Override
        public void onReceivedData(byte[] data) {
            // 1. 将新数据存入缓冲区
            System.arraycopy(data, 0, buffer, bufferPos, data.length);
            bufferPos += data.length;

            // 2. 处理缓冲区中的所有完整帧
            while (bufferPos >= 11) { // 最小帧长度
                // 查找帧头0x55
                if (buffer[0] != (byte)0x55) {
                    // 如果不是帧头，丢弃一个字节
                    System.arraycopy(buffer, 1, buffer, 0, bufferPos - 1);
                    bufferPos--;
                    continue;
                }

                // 检查数据类型
                byte dataType = buffer[1];
                if (dataType == 0x52 || dataType == 0x53) {
                    // 3. 解析有效帧
                    if (bufferPos >= 11) { // 确保有完整帧
                        processFrame(Arrays.copyOfRange(buffer, 0, 11));

                        // 移除已处理的数据
                        System.arraycopy(buffer, 11, buffer, 0, bufferPos - 11);
                        bufferPos -= 11;
                    }
                } else {
                    // 未知数据类型，丢弃
                    System.arraycopy(buffer, 1, buffer, 0, bufferPos - 1);
                    bufferPos--;
                }
            }
        }

        private void processFrame(byte[] frame) {
            // 校验和验证
            byte checksum = 0;
            for (int i = 0; i < 10; i++) checksum += frame[i];
//            Log.d(TAG,"\t校验和: " + " (" + (checksum == frame[10] ? "有效" : "无效") + ")");

            // 根据数据类型解析
            switch (frame[1]) {
                case 0x52: // 角速度
                    float wx = parseValue(frame[2], frame[3], 2000.0f);
                    float wy = parseValue(frame[4], frame[5], 2000.0f);
                    float wz = parseValue(frame[6], frame[7], 2000.0f);
//                    Log.d(TAG,String.format("角速度: X=%.3f°/s Y=%.3f°/s Z=%.3f°/s", wx, wy, wz));
                    updateGyroUI(wx, wy, wz);
                    break;

                case 0x53: // 欧拉角
                    float roll = parseValue(frame[2], frame[3], 180.0f);
                    float pitch = parseValue(frame[4], frame[5], 180.0f);
                    float yaw = parseValue(frame[6], frame[7], 180.0f);
//                    Log.d(TAG,String.format("欧拉角: 横滚=%.3f° 俯仰=%.3f° 航向=%.3f°", roll, pitch, yaw));
                    updateEulerUI(roll, pitch, yaw);
                    break;
            }
        }
    };

//    // 将字节数组转换为十六进制字符串
//    private String bytesToHex(byte[] bytes) {
//        StringBuilder sb = new StringBuilder();
//        for (byte b : bytes) {
//            sb.append(String.format("%02X ", b));
//        }
//        return sb.toString().trim(); // 移除末尾空格
//    }

    // 数据解析方法
    private float parseValue(byte low, byte high, float scale) {
        short value = (short)((high << 8) | (low & 0xFF));
        return value / 32768.0f * scale;
    }

    // 更新角速度UI
    private void updateGyroUI(float wx, float wy, float wz) {
        runOnUiThread(() -> {
            gyroXTextView.setText(String.format("X: %.3f°/s", wx));
            gyroYTextView.setText(String.format("Y: %.3f°/s", wy));
            gyroZTextView.setText(String.format("Z: %.3f°/s", wz));
        });
    }

    // 更新欧拉角UI
    private void updateEulerUI(float roll, float pitch, float yaw) {
        runOnUiThread(() -> {
            rollTextView.setText(String.format("横滚: %.3f°", roll));
            pitchTextView.setText(String.format("俯仰: %.3f°", pitch));
            yawTextView.setText(String.format("偏航: %.3f°", yaw));

            // 更新3D可视化
            mRenderer.updateOrientation(roll, pitch, yaw);
        });
    }

    private void showToast(String message) {
        mainHandler.post(() -> Toast.makeText(Senser.this, message, Toast.LENGTH_SHORT).show());
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        releaseResources();
    }

    private void releaseResources() {
        if (serialPort != null) {
            serialPort.close();
        }
        if (connection != null) {
            connection.close();
        }
    }

}
